package scatter.common.rest.security;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import scatter.common.pojo.vo.ErrorVo;
import scatter.common.rest.tools.InterfaceTool;
import scatter.common.rest.tools.calendar.CalendarUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * scatter默认的登录失败处理器，写入json响应数据
 * Created by yangwei
 * Created at 2020/12/11 13:32
 */
public class DefaultAuthenticationFailureHandler extends DefaultAbstractAuthenticationHandler implements AuthenticationFailureHandler, InterfaceTool {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter out = httpServletResponse.getWriter();
        ErrorVo errorVo = new ErrorVo();
        errorVo.setErrorMsg("用户名或密码不正确");
        out.write(toJsonStr(errorVo));
        out.flush();
        IoUtil.close(out);
        super.tryNotifyIAuthenticationResultServicesOnFailure(httpServletRequest,httpServletResponse,e);
    }
}
